import { createSlice } from '@reduxjs/toolkit';
import { fetchUser, fetchEditUser, fetchLoginOut } from '@/api/user';
import { Dispatch } from '@/interface';
import { Toast } from 'antd-mobile';
import { history } from 'umi';

const initialState = {
  id: undefined,
  username: undefined,
  avatar: undefined,
  phone: undefined,
  sign: undefined,
};

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    restState: state => {
      Object.keys(state).forEach(key => {
        state[key] = undefined;
      });
    },
    changeUser: (state, action) => {
      Object.keys(action.payload).forEach(key => {
        state[key] = action.payload[key];
      });
    },
  },
});

export const { restState, changeUser } = userSlice.actions;

export const loadUser = (params: {}) => {
  return async (dispatch: Dispatch) => {
    const { errorCode, data } = await fetchUser(params);
    if (errorCode === 0) {
      dispatch(changeUser(data));
    }
  };
};

export const loadEditUser = (params: {}) => {
  return async () => {
    const { errorCode } = await fetchEditUser(params);
    if (errorCode === 0) {
      setTimeout(() => {
        Toast.success('操作成功');
      });
      setTimeout(() => {
        history.push('/user');
      }, 1600);
    }
  };
};

export const loadLogout = (params: {}) => {
  return async () => {
    const { errorCode } = await fetchLoginOut(params);
    if (errorCode === 0) {
      setTimeout(() => {
        Toast.success('退出登录成功', 1.5);
      });
      localStorage.clear();
      setTimeout(() => {
        history.push({
          pathname: '/login',
          query: {
            from: location.pathname,
          },
        });
      }, 1500);
    }
  };
};

export default userSlice.reducer;
